package com.lm.flight.config;


import com.google.common.collect.Lists;
import com.lm.flight.example.DemoFlightProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.arrow.flight.*;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.types.pojo.*;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Configuration
public class FlightServerConfig {

    private BufferAllocator allocator;
    private FlightServer flightServer;

    @PostConstruct
    public void startServer() throws Exception {
        allocator = new RootAllocator(Long.MAX_VALUE);

        Location location = Location.forGrpcInsecure("0.0.0.0", 8815);
        flightServer = FlightServer.builder(allocator, location, new DemoFlightProducer(allocator)).build();

        flightServer.start();
        log.info("🚀 Arrow Flight Server started on {}", location);
    }

    @PreDestroy
    public void stopServer() throws Exception {
        if (flightServer != null) {
            flightServer.close();
        }
        allocator.close();
        log.info("🛑 Arrow Flight Server stopped.");
    }
}